<template>
  <edit-card :title="title" :type="type" @confirm="handleConfirm()">
    <div class="form-box">
      <a-form
        ref="formRef"
        :label-col="{ style: { width: '120px' } }"
        style="width: 790px"
        :model="versionFrom"
        label-align="left"
        :rules="rules"
      >
        <a-form-item name="fileList" label="文件" :wrapper-col="{ span: 10 }">
          <div class="w-328">
            <a-upload-dragger
              v-model:fileList="versionFrom.fileList"
              name="file"
              :directory="false"
              :max-count="10"
              :multiple="true"
              :progress="progress"
              :before-upload="beforeUpload"
              :custom-request="customUpload"
              style="height: 120px"
              @drop="drop"
            >
              <div class="upload-content-box">
                <p class="ant-upload-drag-icon"><img src="@/assets/img/modal-base/uploadIdentification.svg" alt="" /></p>
                <p class="ant-upload-text">点击或拖拽上传文件</p>
              </div>
              <template #itemRender="{ file }">
                <upload-file-list :file="file" @on-delete="removeDownload" />
              </template>
            </a-upload-dragger>

            <div class="file-num">{{ versionFrom.fileList.length }}/10条</div>
          </div>
        </a-form-item>
        <div class="versionInp">
          <a-form-item required label="版本号">
            <a-form-item name="versionName" :style="{ marginRight: '12px' }">
              <a-select
                v-model:value="versionFrom.versionName"
                style="width: 328px"
                placeholder="请选择版本号"
                :field-names="{ label: 'version', value: 'id' }"
                :options="versionOption"
                :get-popup-container="(triggerNode: any) => triggerNode.parentNode"
              />
            </a-form-item>
            <a-form-item v-if="versionFrom.versionName === 'add-version'" name="versionInput">
              <a-input v-model:value="versionFrom.versionInput" v-trim :maxlength="10" placeholder="例如：1.0.1" style="width: 328px" />
            </a-form-item>
          </a-form-item>
        </div>

        <a-form-item class="form-item" label="描述" name="describe">
          <div class="w-328">
            <a-textarea
              v-model:value="versionFrom.describe"
              placeholder="请输入描述"
              :auto-size="{ minRows: 8 }"
              :maxlength="200"
              show-count
            />
          </div>
        </a-form-item>
      </a-form>
    </div>
  </edit-card>
  <a-modal
    v-model:open="visibleModal"
    centered
    width="416px"
    :mask-closable="false"
    :body-style="{ 'padding-bottom': '0' }"
    ok-text="退出"
    @ok="handleOk"
    @cancel="resetForm"
  >
    <a-spin :spinning="isLoading" tip="加载中">
      <div class="tips">
        <span class="icon"><i class="iconfont icon-error-warning-fill"></i></span>
        {{ `文件正在上传中,确认退出此页面?` }}
      </div>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
  import { message, Modal, UploadProps } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { axios, debounce, storage } from 'g6-fn'
  import { computed, createVNode, reactive, ref } from 'vue'
  import { onBeforeRouteLeave, useRoute, useRouter } from 'vue-router'

  import UploadFileList from '@/components/UploadFileList/index.vue'
  import { modelLibraryApi } from '@/services/api'
  import { countStrToBit } from '@/utils'

  import { uploadApi } from './store'
  interface VersionOption {
    id: string
    version: string
  }
  interface ListObject {
    uuid: string
    name: string
    type: string | undefined
    size: number
  }

  interface MyObject {
    modelBaseId: string
    version?: string
    versionId?: string
    description: string
    list: ListObject[]
  }

  type FileObject = {
    uuid: string
    name: string
    type: string
    size: number
  }
  const route = useRoute()
  const router = useRouter()
  const { id } = route.params as { id: string }

  console.log(id, 'idid')

  const type = 'add'
  const title = computed(() => (type === 'add' ? '上传文件' : ''))
  // 表单
  const formRef = ref()
  let versionFrom = reactive({
    fileList: [],
    versionName: undefined,
    versionInput: '',
    describe: ''
  })

  const fileListValidator = async () => {
    let successfulFileList = versionFrom.fileList?.filter((item: any) => item.status === 'done' || item.status === 'uploading')
    if (successfulFileList.length === 0) {
      return Promise.reject('请上传文件')
    }
    return Promise.resolve()
  }

  const rules: Record<string, Rule[]> = {
    versionName: [{ required: true, message: '请选择版本号', trigger: 'change' }],
    fileList: [{ validator: fileListValidator }],
    versionInput: [
      { required: true, message: '请输入版本号名称', trigger: 'change' },
      {
        pattern: /^(?!\.)(\d+\.)*\d+$/,
        message: '仅支持数字和小数点,且以数字结尾'
      }
    ],
    describe: [{ required: false, message: '请输入描述' }]
  }
  //进度条
  const progress: UploadProps['progress'] = {
    strokeColor: {
      '0%': '#1868E9',
      '100%': '#1868E9'
    },
    strokeWidth: 3,
    format: (percent: any) => `${parseFloat(percent?.toFixed(2))}%`,
    class: 'progress'
  }

  let fileNum = 0
  const beforeUpload = (file: any) => {
    // 控制文件名大小
    if (countStrToBit(file.name) > 200) {
      file.status = 'error'
      file.message = '文件名超出长度'
      return Promise.reject()
    }
    fileNum++
    if (fileNum > 10) {
      fileNum = 10
      return Promise.reject()
    }

    return Promise.resolve()
  }

  /* 内部上传逻辑 */
  let CancelToken /* 取消请求令牌 */ = axios.CancelToken
  const source = CancelToken.source()
  const customUpload = async (e: any) => {
    const { file } = e
    e.file.status = 'wait'
    e.file.percent = 0
    uploadApi({
      file,
      onUploadProgress: (Progress: { loaded: number; total: number }) => {
        let percents = Math.round((Progress.loaded / Progress.total) * 100)
        e.onProgress({ percent: percents > 99 ? 99 : percents })
        e.file.progress = percents > 99 ? 99 : percents
      },
      modelBaseId: id,
      source
    })
      .then((res: any) => {
        e.onSuccess(res, e)
      })
      .catch((err: any) => {
        e.onError(err)
        versionFrom.fileList?.forEach((item: any) => {
          if (item.uid === file.uid) {
            item.status = 'error'
            item.message = '上传失败'
          }
        })
      })
  }

  const removeDownload = async (e: any) => {
    e.cancelToken?.cancel('用户取消上传')
    const params = [
      {
        list: [
          {
            uuid: e.uuid,
            type: e.name.split('.').pop()
          }
        ],
        modelBaseId: id
      }
    ]
    const { data } = await modelLibraryApi.deleteNotUploaded(params, {
      isAddUid: true
    })
    if (data) {
      const storedIds = storage.get('uploadModelFile') || []
      const filteredIds = storedIds.filter((item: any) => item.list[0].uid !== e.uid)
      versionFrom.fileList = versionFrom.fileList.filter((item: any) => item.uid !== e.uid)
      storage.set('uploadModelFile', filteredIds)
      console.log(fileNum, 'fileNum')
      fileNum--
    }
  }

  //版本号
  const versionOption = ref<VersionOption[]>([])
  const drop = (e: any) => {
    let items = e.dataTransfer.items
    for (let i = 0; i <= items.length - 1; i++) {
      let item = items[i]
      if (item.kind === 'file') {
        // FileSystemFileEntry 或 FileSystemDirectoryEntry 对象
        let entry = item.webkitGetAsEntry()
        // 是文件夹
        if (entry && entry.isDirectory) {
          // 过滤 versionFrom.fileList
          const filteredFileList = versionFrom.fileList.filter((item: any) => item.name !== entry.name)
          // 更新 versionFrom.fileList
          versionFrom.fileList = filteredFileList
          message.warning('不允许上传文件夹', 2)
        }
      }
    }
  }
  const uploadTags = ref<boolean>(false)
  //点击确定
  const handleConfirm = debounce(async (): Promise<void> => {
    await formRef.value.validateFields()
    uploadTags.value = false
    const validFiles = versionFrom.fileList.filter((file: any) => file.status === 'done')
    const uploadingFile = versionFrom.fileList.find((file: any) => file.status === 'uploading')
    if (uploadingFile) {
      message.warning('文件正在上传中', 2)
      return
    }
    const result = validFiles.map((file: FileObject) => ({
      uuid: file.uuid,
      name: file.name,
      type: file.name.split('.').pop(),
      size: file.size
    }))
    const params: MyObject = {
      modelBaseId: id,
      list: result,
      description: versionFrom.describe
    }
    if (versionFrom.versionName === 'add-version') {
      params.version = versionFrom.versionInput
    } else {
      params.versionId = versionFrom.versionName
    }

    try {
      await modelLibraryApi.uploadModel(params, { isAddUid: true })
      message.success('上传成功')
      uploadTags.value = true
      // 从 localStorage 中获取存储的文件 ID 数组
      const storedIds = storage.get('uploadModelFile') || []

      // 过滤出需要删除的项
      const filteredIds = storedIds.filter(
        (param: any) => !param.list.some((item: any) => result.some(resultItem => resultItem.uuid === item.uuid))
      )

      // 更新 localStorage 中的文件 ID 数组
      if (filteredIds.length) {
        storage.set('uploadModelFile', filteredIds)
      } else {
        storage.remove('uploadModelFile')
      }

      versionFrom.fileList = []
      router.go(-1)
    } catch (error) {}
  }, 500)
  //点击取消

  //离开页面退出操作
  const visibleModal = ref<boolean>(false)
  const isLoading = ref<boolean>(false)
  //检查uploadingFileId并进行处理

  const checkTheUploadList = async (): Promise<void> => {
    // 检查 localStorage 中是否存在 'uploadModelFile' 这个键
    const storedParams = storage.get('uploadModelFile')
    console.log(storedParams, '000')

    if (storedParams) {
      try {
        const params = storedParams
        console.log(params, 'storedParams')
        // 调用后端的上传完成接口
        const { data } = await modelLibraryApi.deleteNotUploaded(params, {
          isAddUid: true
        })

        if (data) {
          storage.remove('uploadModelFile')
          console.log('删除成功')
        }
        //
      } catch (error) {}
    }
  }

  onBeforeRouteLeave((to, from, next) => {
    if (uploadTags.value) {
      next()
    } else {
      Modal.confirm({
        content: createVNode('div', { style: 'color:gba(0, 0, 0, 0.75);' }, '确认退出上传文件页面?'),
        okText: '退出',
        centered: true,
        onOk: debounce(() => {
          console.log('OK')
          checkTheUploadList()
          next()
        }, 500),
        onCancel() {
          console.log('Cancel')
          next(false)
        },
        class: 'test'
      })
    }
  })

  const handleOk = async () => {
    console.log('handleOk')

    resetForm()
  }
  const resetForm = () => {
    visibleModal.value = false
  }

  //已有版本号
  const queryVersionNumber = async (): Promise<void> => {
    const res = await modelLibraryApi.existingVersionNumber({ modelBaseId: id })
    versionOption.value = res.data.map((item: VersionOption) => item).concat([{ id: 'add-version', version: '新增版本' }])
  }

  queryVersionNumber()
</script>

<style lang="less" scoped>
  :deep(textarea::-webkit-scrollbar) {
    display: none !important;
  }

  :deep(.ant-upload-list-text-container) {
    transition: none;
  }

  :deep(.ant-upload-list) {
    display: inline-block;
    width: 328px;
  }

  :deep(.ant-anchor-ink-ball) {
    left: -50%;
    width: 2px;
    height: 22px;
    border-radius: 0;
    transform: translate(0, -7px);
  }

  :deep(.ant-upload-picture-card-wrapper) {
    width: 140px;
  }

  :deep(.ant-form-item) {
    margin-bottom: 40px;
  }

  :deep(.ant-form-item-label > label) {
    min-width: 120px;
  }

  // :deep(.ant-input-textarea-show-count::after) {
  //   position: absolute;
  //   right: 12px;
  //   bottom: 8px;
  // }

  .tips {
    display: flex;
    margin-top: 16px;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.75);
    line-height: 24px;

    .icon {
      margin-right: 10px;
      font-size: 24px;
      color: #f59700;

      i {
        font-size: 24px;
      }
    }
  }

  :deep(.ant-upload-list-item) {
    max-width: 800px;
    height: 40px !important;
    white-space: normal;
    word-break: break-all;
    word-wrap: break-word;
    // margin-top: 0 !important;
  }

  :deep(.ant-motion-collapse) {
    height: unset !important;
  }

  :deep(.ant-upload-drag) {
    width: 328px;
    height: 120px;
  }
  // :deep(.ant-btn-sm) {
  //   height: 40px;
  // }

  .versionInp {
    .ant-form-item {
      display: inline-block;
      margin-bottom: 20px;
    }
  }

  .w-328 {
    width: 328px;
  }

  .upload-content-box {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 16px;
    width: 100%;
    height: 100%;
    flex-direction: column;
    gap: 8px 0;

    .ant-upload-text {
      font-size: 12px;
      text-align: center;
      color: rgba(0, 0, 0, 0.75);
      font-weight: 400;
      line-height: 20px;
    }
  }

  .file-num {
    transform: translateY(-2px);
  }

  :deep(.ant-upload-drag-icon) {
    margin-bottom: 0 !important;
  }
</style>
